#include<QtGui>
#include "marquee.h"

Marquee::Marquee(QWidget *parent)
: QWidget(parent)
{
	offset = 0;
    myTimerId = 0;
    setFont(QFont("Arial",6));
}
void Marquee::stop(){killTimer(myTimerId);}
void Marquee::start(){myTimerId = startTimer(30);}
void Marquee::fromFile(const QString & filename){
	QFile data(QString("%1.%2").arg(filename).arg("txt"));
	if (data.open(QFile::ReadOnly)){
		QTextStream fin(&data);
		fin.setCodec("UTF-8");
		//fin.setAutoDetectUnicode(true);
		setText(fin.readAll().replace(QChar('\n')," "));
	}else setText("sorry");
	data.close();
}
void Marquee::setText(const QString &newText)
{
    myText = newText;
    offset = 0;
    update();
    updateGeometry();
}

QSize Marquee::sizeHint() const
{
    return fontMetrics().size(0, text());
}

void Marquee::paintEvent(QPaintEvent * /* event */)
{
    QPainter painter(this);
	painter.setBrush(Qt::white);
	painter.setPen(Qt::gray);
	painter.drawRect(0,0,width()-1,height()-1);
    int textWidth = fontMetrics().width(text()) + 50;
    if (textWidth < 1)
        return;
    int x = -offset;
    
    while (x < width()) {
        painter.drawText(painter.boundingRect(x, 0,textWidth, height(),Qt::AlignLeft | Qt::AlignVCenter, text()), text());
//          painter.drawText(rect(),Qt::AlignLeft | Qt::AlignVCenter, text());
        x += textWidth;
    }
}
void Marquee::showEvent(QShowEvent * /* event */)
{
    myTimerId = startTimer(30);
}
void Marquee::timerEvent(QTimerEvent *event)
{
    if (event->timerId() == myTimerId) {
        ++offset;
        
        if (offset >= fontMetrics().width(text())+50)
            offset = 0;
        scroll(-1, 0);
    } else {
        QWidget::timerEvent(event);
    }
}
void Marquee::hideEvent(QHideEvent * /* event */)
{
    killTimer(myTimerId);
}
